package shun.demo.process.monitor;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;

import java.util.List;
import java.util.Observable;

/**
 * Created by chen on 14-4-1.
 */
public class ActivityMonitor extends Observable {

    private static final int DELAY_MILLIS = 1000;
    private ActivityManager mActivityManager;
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private Context mContext;

    public ActivityMonitor(Context context) {
        mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        mContext = context;
    }

    public void start() {
        // start only once
        if (mHandlerThread == null) {
            mHandlerThread = new HandlerThread("ActivityMonitor");
            mHandlerThread.start();
            mHandler = new Handler(mHandlerThread.getLooper());
            mHandler.post(mRunnable);
        }
    }

    public void stop() {
        if (mHandlerThread != null) {
            mHandlerThread.quit();
            mHandlerThread = null;
        }
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            ComponentName componentName = getForegroundActivity();
            setChanged();
            notifyObservers(componentName);
            mHandler.postDelayed(this, DELAY_MILLIS);
        }
    };

    private ComponentName getForegroundActivity() {
        List<ActivityManager.RunningTaskInfo> taskInfos = mActivityManager.getRunningTasks(1);
        if (taskInfos != null) {
            return taskInfos.get(0).topActivity;
        }
        return null;
    }
}
